import { MutationTree } from 'vuex';
import { UserState } from './typing';
import { state as initState } from './state';
import ls from '@/utils/local-storage';
import { STORAGE_TOKEN_KEY } from '@/store/mutation-type';
import { setUserFactory } from '@/utils/user-util';

export const SET_TOKEN = 'SET_TOKEN';
export const SET_ROUTES = 'SET_ROUTES';
export const SET_USER = 'SET_USER';
export const SET_ROUTERS = 'SET_ROUTERS';
export const RESET_CURRENT_USER = 'RESET_CURRENT_USER';
export const SET_MENU_KEY_MAP = 'SET_MENU_KEY_MAP';
export const CURRENT_FACTORY = 'CURRENT_FACTORY';
export const MULTI_FACTORY_CHANGE = 'MULTI_FACTORY_CHANGE';

export const mutations: MutationTree<UserState> = {
  [SET_TOKEN]: (state: UserState, token: string) => {
    state.token = token;
    ls.set(STORAGE_TOKEN_KEY, token);
  },
  [SET_USER]: (state, user) => {
    state.user = user;
  },
  [SET_ROUTERS]: (state, routers) => {
    state.routers = routers;
  },
  [SET_ROUTES]: (state, routes) => {
    state.routes = routes;
  },
  [RESET_CURRENT_USER]: state => {
    Object.assign(state.user, initState.user);
  },
  [SET_MENU_KEY_MAP]: (state, menuKeyMap) => {
    state.menuKeyMap = menuKeyMap;
  },
  [CURRENT_FACTORY]: (state, currentFactory) => {
    state.currentFactory = currentFactory;
    setUserFactory(currentFactory);
  },
  [MULTI_FACTORY_CHANGE]: (state, multiFactoryChange) => {
    state.multiFactoryChange = multiFactoryChange;
  },
};
